class Event {
  cache
  constructor() {
    this.cache = {}
  }
  // 监听
  on(eventType, fun) {
    (this.cache[eventType] || (this.cache[eventType] = [])).push(fun)
  }
  // 执行一次就销毁
  once(eventType,fun){
    function on(){
      this.off(eventType,on)
      fun.apply(this,arguments)
    }
    this.on(eventType,on)
  }
  // 移除监听
  off(eventType, fun) {
    // 没传，就移除所有监听，传了就移除传的函数
    if (fun) {
      let arr = this.cache[eventType]
      if (arr) {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i] == fun) {
            arr.splice(i, 1)
            break
          }
        }
      }
    } else {
      delete this.cache[eventType]
    }
  }
  // 通知
  emit(eventType,...args){
    let arr = this.cache[eventType]
    if(arr&&arr.length>0){
      arr.forEach(item=>{
        item.apply(this,args)
      })
    }
  }
}
export default Event